package com.xbongbong.workorder.explain;/*/*/

import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.VisibleRuleVO;
import com.xbongbong.paas.help.OwnerAndCoUserHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.util.DepartmentFieldUtil;
import com.xbongbong.saas.util.UserFieldUtil;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.RoleEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workorder.abstracts.AbstractWorkOrderFromExplainHandlerName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author 魏荣杰
 * @date 2019/4/8 21:58
 * @since v1.0
 * @version v1.0
 */
@Component
public class WorkOrderFormDataFormExplainHandleName extends AbstractWorkOrderFromExplainHandlerName {

    private static final Logger LOG = LoggerFactory.getLogger(WorkOrderFormDataFormExplainHandleName.class);

    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private OwnerAndCoUserHelp ownerAndCoUserHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;

    public HandlerExplainVO handlerExplain(HandlerExplainDTO handlerExplainDTO, List<FieldAttrEntity> explainList, WorkOrderFormEntityExt formEntity, WorkOrderEntity workOrderEntity) throws XbbException {
        Integer businessType = handlerExplainDTO.getBusinessType();
        Integer saasMark = handlerExplainDTO.getSaasMark();
        Set<String> userIdList = UserFieldUtil.getUserIdList(explainList, workOrderEntity);
        userIdList.addAll(handlerExplainDTO.getOwnerId());
        userIdList.addAll(handlerExplainDTO.getCoUserId());
        List<UserEntity> list = userModel.getByUserIdIn(handlerExplainDTO.getCorpid(), userIdList, null);
        Map<String, UserEntity> userMap = new HashMap<>(list.size());
        list.forEach(item->{
            userMap.put(item.getUserId(), item);
        });
        Set<Long> departmentIdList = DepartmentFieldUtil.getDepartmentIdList(explainList, workOrderEntity);
        List<DepartmentEntity> departmentList = departmentModel.getDepartmentNamesByIds(handlerExplainDTO.getCorpid(), departmentIdList, false);
        Map<String, DepartmentEntity> departmentMap = new HashMap<>(departmentList.size());
        departmentList.forEach(item->{
            departmentMap.put(item.getId().toString(), item);
        });
        // 获取协同人和负责人（产品是可见人可见部门）
        handlerExplainDTO.setExplainList(explainList);
        ownerAndCoUserHelp.getOwnerIdAndCoUserId(handlerExplainDTO, saasMark, businessType, workOrderEntity, userMap, DelEnum.NORMAL.getDel());
        handlerExplainDTO.setCreatorId(workOrderEntity.getCreatorId());
        handlerExplainDTO.setExplainList(explainList);
        // 获取协同人和负责人
        PaasFormDataEntityExt paasFormDataEntity = new PaasFormDataEntityExt();
        BeanUtil.copyProperties(workOrderEntity, paasFormDataEntity);

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, handlerExplainDTO.getCorpid());
        param.put("appId", formEntity.getAppId());
        param.put("formId", formEntity.getId());

        HandlerExplainVO handlerExplainVO = handlerExplain(explainList, formEntity,param, handlerExplainDTO);
        handlerExplainVO.setCoUserId(handlerExplainDTO.getCoUserId());
        handlerExplainVO.setOwnerId(handlerExplainDTO.getOwnerId());
        handlerExplainVO.setUserMap(userMap);
        handlerExplainVO.setDepartmentMap(departmentMap);
        return handlerExplainVO;
    }

    @Override
    public HandlerExplainVO handlerExplain(List<FieldAttrEntity> explainList, WorkOrderFormEntityExt workOrderFormEntityExt, Map<String, Object> param, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        HandlerExplainVO handlerExplainVO = new HandlerExplainVO();
        try {
            Map<String, Object> explainParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            explainParam.put("corpid", param.get("corpid"));
            explainParam.put("appId", param.get("appId"));
            explainParam.put("formId", param.get("formId"));
            List<WorkOrderExplainEntity> formExplainList = workOrderExplainModel.list(explainParam);
            if (formExplainList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            Map<String, WorkOrderExplainEntity> formExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            formExplainList.forEach((item) -> {
                formExplainMap.put(item.getFormId().toString(), item);
            });

            handlerExplainVO = getExplainList(explainList, param, formExplainMap, handlerExplainDTO);

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("WorkOrderFormDataFormExplainHandleName.handlerExplain 处理字段中的部门、角色、用户等名称报错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return handlerExplainVO;
    }

    /**
     * Description:
     * @param explainList
     * @param param
     * @param formExplainMap
     * @param handlerExplainDTO
     * @return com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO
     * @throws XbbException XbbException
     * @author 魏荣杰
     * @date 2019/4/11 16:41
     * @since v1.0
     */
    public HandlerExplainVO getExplainList(List<FieldAttrEntity> explainList, Map<String, Object> param, Map<String, WorkOrderExplainEntity> formExplainMap, HandlerExplainDTO handlerExplainDTO) throws XbbException{
        HandlerExplainVO handlerExplainVO = new HandlerExplainVO();
        //用户集合
        Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //部门集合
        Map<String, DepartmentEntity> departmentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //角色集合
        Map<String, RoleEntity> roleMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<FieldAttrEntity> list = new ArrayList<>();
        try {
            for (FieldAttrEntity entity : explainList) {
                /*if (FieldTypeEnum.COUSERID.getType().equals(entity.getFieldType())) {
                    continue;
                }
                if (FieldTypeEnum.OWNERID.getType().equals(entity.getFieldType())) {
                    continue;
                }*/
                // 允许可见，则处理以下规则
                if(entity.getVisible().equals(1)){
                    List<VisibleRuleVO> userVoList = new ArrayList<>();
                    if (Objects.equals(entity.getIsRedundant(),0) && Objects.equals(entity.getIsOpen(), 0)) {
                        // 非扩展字段，并且未开启时，字段不能显示在列表上
                        continue;
                    }
                    if (Objects.equals(entity.getIsOpen(), 2)) {
                        continue;
                    }
                    // 高级可见规则回显用户名称
                    if (ExplainUtil.invisibleOfScope(entity, handlerExplainDTO)) {
                        continue;
                    }
                    if(ExplainUtil.isSubForm(entity.getFieldType())){
                        setSubFieldAttrEntity(entity, param, userMap, departmentMap, roleMap, formExplainMap, handlerExplainDTO);
                    }else{
                        entity = setFieldAttrEntity(entity, handlerExplainDTO, userMap, departmentMap, roleMap, formExplainMap);
                    }
                    if (Objects.nonNull(entity.getVisibleScopeRule())) {
                        entity.getVisibleScopeRule().setUserList(userVoList);
                    }
                    list.add(entity);
                }
            }

            handlerExplainVO.setHeadList(list);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("WorkOrderFormDataFormExplainHandleName.getExplainList处理字段中的部门、角色、用户等名称报错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return handlerExplainVO;
    }
}
